// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const fakeCards = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,32,33,35,53,54,55];
const pockerNum = cc.Class({
    name: "pockerNum",
    properties:{
        default:[],
        type: [cc.SpriteFrame]
    }
})
const pockerColor = cc.Class({
    name: "pockerColor",
    properties:{
        default:[],
        type: [cc.SpriteFrame]
    }
})
cc.Class({
    extends: cc.Component,

    properties: {
        myHandCards: {
            default: [],
            type: [cc.Integer]
        },
        bucket: {
            default: [],
            type: [cc.Node]
        },
        pokerPrefab: {
            default: null,
            type: cc.Prefab
        },
        bjPrefab:{
            default: null,
            type: cc.Prefab
        },
        rjPrefab:{
            default: null,
            type: cc.Prefab
        },
        pockerNum :{
            default:[],
            type: [cc.SpriteFrame]
        },
        pockerColor :{
            default:[],
            type: [cc.SpriteFrame]
        },
        cardIns:{
            default: null,
            type: cc.Node
        },
        pockerShowPrefab:{
            default: null,
            type: cc.Prefab
        }
        
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
        myHandCards = [1,2,3,14,15,16];
        this.myDisplay = []
        // this is for test
        //this._showCard();
        this.showSingleCard(0);
        this.activeClock(0);

        this.ws = new WebSocket("ws://localhost:30000/msg?room=123&seat=1");
        let that = this;
        this.ws.onopen = function(evt) {
            console.log("Connection open ...");
            that.ws.send("Hello WebSockets!");
        };
        
        this.ws.onmessage = function(evt) {
            console.log("Received Message: " + evt.data);
            //obj = JSON.parse(evt.data);
            
            //that.ws.close();
        };
        
        this.ws.onclose = function(evt) {
            console.log("Connection closed.");
        };

    },
    activeClock(index){
        cc.log("clock start");
        const c_pos = [[0,-110],[-200,100],[200,100],[0,170]];
        let clock = cc.find("Canvas/bg_game/count_down");
        clock.x = c_pos[index][0];
        clock.y = c_pos[index][1];
        let comp = cc.find("Canvas/bg_game/count_down/secd").getComponent(cc.Label);
        let time = 20;
        this.schedule(function(){
            time--;
            comp.string = time+"";
        },1);
    },

    showSingleCard(x){
        let card = this._createCard(x)
        this.node.addChild(card);
        card.x = 200;
        card.y = 300;

    },

    // update (dt) {},
    _showCard(){
        for(let i=0;i<this.bucket.length;i++){
            this.bucket[i].destroy();
        }
        for(let i=0;i<myHandCards.length;i++){
            let card = this._createCard(myHandCards[i],false);
            cc.log('card',card);
            this.bucket.push(card);
        }
        this._arrange();
        this._addCards();
    },

    _addCards(){
        for(let i=0;i<this.cardArea.length;i++){
            for(let j=this.cardArea[i].length-1;j>=0;j--){
                this.node.addChild(this.cardArea[i][j]);
            }
            
        }
    },

    _arrange(){
        cc.log("arrange",this.cardArea);
        this.cardArea = [];
        for(let i=0;i<17;i++){
            this.cardArea[i] = [];
        }
        for(let i=0;i<this.bucket.length;i++){
            let node = this.bucket[i];
            let compo = node.getComponent("card");
            if(compo.num==1000){
                this.cardArea[16].push(node);
            }
            else if(compo.num==2000){
                this.cardArea[17].push(node);
            }
            else{
                this.cardArea[compo.num].push(node);
            }
        }
        let validCnt = 0;
        for(let i=0;i<this.cardArea.length;i++){
            if(this.cardArea[i].length>0){
                validCnt++;
            }
        }
        let index = 0;
        let gap = Math.min(60,600/validCnt);
        let nodeCnt = 0;
        for(let i=0;i<this.cardArea.length;i++){
            cc.log(this.cardArea[i]);
            for(let j=0;j<this.cardArea[i].length;j++){
                let node = this.cardArea[i][j];
                node.x = -220 + gap * index;
                node.y = -400 + 25*j;  
                nodeCnt++;
            }
            if(this.cardArea[i].length>0){
                index++;
            }
        }
        cc.log("arrange节点数量",nodeCnt);
    },

    _createCard(cardId,display){
        if(cardId==1000){
            let card = cc.instantiate(this.bjPrefab);//返回一个Node类型
            let cardComponent = card.getComponent("card");
            cardComponent.id = 1000;
            cardComponent.num = 1000;
            cardComponent.color = 5;
            return card;
        }
        else if(cardId==2000){
            let card = cc.instantiate(this.rjPrefab);
            let cardComponent = card.getComponent("card");
            cardComponent.id = 2000;
            cardComponent.num = 2000;
            cardComponent.color = 5;
            return card;
        }
        else{
            let card;
            if(display){card = cc.instantiate(this.pockerShowPrefab);}
            else {card = cc.instantiate(this.pokerPrefab);}
            let cardComponent = card.getComponent("card");
            let cardNumNode = card.getChildByName("num");
            let cardColorNode = card.getChildByName("type");
            let cardColorSNode = card.getChildByName("types");
            //cc.log('aaa',cardId);
            [num,color,s] = this._getCard(cardId);
            cc.log(num,color,s);
            cardComponent.id = cardId;
            cardComponent.num = num;
            cardComponent.color = color;
            cardColorNode.getComponent(cc.Sprite).spriteFrame = this.pockerColor[color];

            if(s==null||color%2==0)cardNumNode.getComponent(cc.Sprite).spriteFrame = this.pockerNum[num];
            else cardNumNode.getComponent(cc.Sprite).spriteFrame = this.pockerNum[num+13];

            if(s!=null)cardColorSNode.getComponent(cc.Sprite).spriteFrame = this.pockerColor[color];
            else cardColorSNode.getComponent(cc.Sprite).spriteFrame = null;
            return card;
        }
    },

    _getCard(x){
        if(x==2000){
            return [27,6,null];
        }
        else if(x==1000){
            return [26,5,null];
        }
        else{
            return [x%13,Math.floor(x%52/13),Math.floor(x%52/13)];
        }
    },

    playAHand(){
        let toPlayList = this._getSelected();
        if(this.checkAHand(toPlayList)){
            cc.log("通过了检查");
            this._delSelected(toPlayList);
            this.displaySelected(toPlayList);
            this._destroyPlayed(toPlayList);
            this._arrange();
        }
    },

    _destroyPlayed(toPlayList){
        for(let i=0;i<toPlayList.length;i++){
            toPlayList[i].destroy();
        }
    },

    _getSelected(){
        let selList = [];
        let loc = []
        for(let i=0;i<this.cardArea.length;i++){
            for(let j=0;j<this.cardArea[i].length;j++){
                if(this.cardArea[i][j].getComponent("card").select){
                    selList.push(this.cardArea[i][j]);
                    loc.push([i,j]);
                }
            }
        }
        return selList;
    },

    checkAHand(){
        return true;
    },

    _delSelected(toPlayList){
        let index = 0;
        for(let i=0;i<this.cardArea.length;i++){
            for(let j=0;j<this.cardArea[i].length;j++){
                if(toPlayList[index]==this.cardArea[i][j]){
                    for(let k=0;k<this.myHandCards.length;k++){
                        if(this.myHandCards[k]==this.cardArea[i][j].getComponent("card").id){
                            this.myHandCards.splice(k,1);
                            break;
                        }
                    }
                    this.cardArea[i].splice(j,1);
                    index++;
                }
            }
            cc.log(this.cardArea[i]);
        }cc.log(this.cardArea);
        for(let i=0;i<toPlayList.length;i++){
            for(let j=0;j<this.bucket.length;j++){
                if(toPlayList[i]==this.bucket[j]){
                    this.bucket.splice(j,1);
                    break;
                }
            }
        }
         
    },

    displaySelected(toPlayList){
        for(let i=0;i<toPlayList.length;i++){
            let id = toPlayList[i].getComponent("card").id;
            let card = this._createCard(id,true);
            this.myDisplay.push(card);
            this.node.addChild(card);
            card.x = -100 + i * 20;
            card.y = -100
        }
    },

    onInvite(res) {
        let item = {
            id: this.id
        }
        wx.shareAppMessage({
            title: '邀请好友助力',
            path: '/pages/group_detail/group_detail?id=' + this.id,
            //path: '/pages/group_detail/group_detail?item=' + encodeURIComponent(JSON.stringify(item)),
            success: (res) => {
                // 转发成功
                console.log("转发成功:" + JSON.stringify(res));
            },
            fail: function(res) {
                // 转发失败
                console.log("转发失败:" + JSON.stringify(res));
            }
        })
    },

});
